﻿using System;
using System.Net;
using System.Net.Sockets;

using LoginServer.Manager;

namespace LoginServer.Networking
{
    class NetworkSocket
    {
        private static Socket _Socket;

        public static bool openSocket(int Port)
        {
            _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //_AcceptedConnections = 0;

            try
            {

                _Socket.Bind(new IPEndPoint(IPAddress.Any, Port));
                _Socket.Listen(25);
                _Socket.BeginAccept(new AsyncCallback(acceptConnection), _Socket);
                Log.WriteLine("Accepting login requests from port " + Port);
                return true;
            }
            catch
            {
                Log.WriteError("Error while setting up asynchronous the socket server for connections on port " + Port + ".");
                Log.WriteError("Port " + Port + " could be invalid or in use already.");
            }

            return false;
        }

        private static void acceptConnection(IAsyncResult iAr)
        {
            try
            {
                Socket uSocket = ((Socket)iAr.AsyncState).EndAccept(iAr);

                string IP = uSocket.RemoteEndPoint.ToString().Split(':')[0];
                if (BanManager.isBanned(uSocket.RemoteEndPoint.ToString().Split(':')[0], Dns.GetHostEntry(uSocket.RemoteEndPoint.ToString().Split(':')[0]).HostName) == false)
                {
                    string IPBanned = new WebClient().DownloadString(Environment.CurrentDirectory + "\\bannedip.txt");
                    if (!IPBanned.Contains(IP))
                    {
                        Log.WriteLine("Accepted a connection from: " + uSocket.RemoteEndPoint);
                        Virtual_Objects.User.virtualUser UserObj = new Virtual_Objects.User.virtualUser(uSocket);
                    }
                }
                else
                {
                    Log.WriteLine("Refused a connection from: " + uSocket.RemoteEndPoint);
                    //DB.runQuery("INSERT INTO log_connections (`timestamp`, `server`, `status`, `ip`, `host`) VALUES ('" + Program.UnixTimestamp + "', '0', '-1', '" + uSocket.RemoteEndPoint.ToString().Split(':')[0] + "', '" + Dns.GetHostEntry(uSocket.RemoteEndPoint.ToString().Split(':')[0]).HostName + "');");
                }
            }
            catch { }
            _Socket.BeginAccept(new AsyncCallback(acceptConnection), _Socket);
        }
    }
}
